import 'dart:async';
import 'dart:math';
import 'package:audioplayers/audioplayers.dart';
import '../models/song.dart';
import 'dart:io';

class AudioPlayerService {
  static final AudioPlayerService _instance = AudioPlayerService._internal();
  factory AudioPlayerService() => _instance;

  final AudioPlayer _audioPlayer = AudioPlayer();
  Song? _currentSong;
  List<Song> _playlist = [];
  bool _isRandomPlay = false;
  final Random _random = Random();
  final StreamController<double> _volumeController = StreamController<double>.broadcast();
  double _currentVolume = 0.4; // 默认音量为最大

  AudioPlayerService._internal() {
    // 初始化音量
    _audioPlayer.setVolume(_currentVolume);
  }

  // 设置音量
  Future<void> setVolume(double value) async {
    try {
      await _audioPlayer.setVolume(value);
      _currentVolume = value;
      _volumeController.add(value); // 通知监听器
    } catch (e) {
      print('设置音量失败: $e');
      rethrow;
    }
  }
  // 获取当前音量
  double get currentVolume => _currentVolume;
  // 获取音量流
  Stream<double> get volumeStream => _volumeController.stream;

  Song? get currentSong => _currentSong;
  AudioPlayer get player => _audioPlayer;
  bool get isRandomPlay => _isRandomPlay;

  // 获取播放位置变化流
  Stream<Duration> get positionStream => _audioPlayer.onPositionChanged;
  // 获取音频时长流
  Stream<Duration> get durationStream => _audioPlayer.onDurationChanged;
  // 获取播放状态流
  Stream<PlayerState> get playingStream => _audioPlayer.onPlayerStateChanged;

  void setPlaylist(List<Song> songs) {
    _playlist = songs;
  }

  void toggleRandomPlay() {
    _isRandomPlay = !_isRandomPlay;
  }

  Future<void> playNext() async {
    if (_playlist.isEmpty || _currentSong == null) return;

    int nextIndex;
    if (_isRandomPlay) {
      nextIndex = _random.nextInt(_playlist.length);
    } else {
      int currentIndex = _playlist.indexWhere((song) => song.songId == _currentSong?.songId);
      nextIndex = (currentIndex + 1) % _playlist.length;
    }

    await playSong(_playlist[nextIndex]);
  }

  Future<void> playSong(Song song) async {
    if (!song.isDownloaded || song.localPath == null) {
      throw Exception('歌曲未下载');
    }

    try {
      final file = File(song.localPath!);
      if (!await file.exists()) {
        throw Exception('音频文件不存在: ${song.localPath}');
      }

      print("paly ${file.path}");
      await _audioPlayer.setSource(DeviceFileSource(file.path));
      _audioPlayer.seek(Duration.zero);
      await _audioPlayer.resume();

      _currentSong = song;

      // 设置播放完成后的回调
      _audioPlayer.onPlayerStateChanged.listen((state) {
        if (state == PlayerState.completed) {
          playNext();
        }
      });

    } catch (e) {
      print('播放失败: $e');
      rethrow;
    }
  }

  Future<void> togglePlay() async {
    try {
      if (_audioPlayer.state == PlayerState.playing) {
        await _audioPlayer.pause();
      } else {
        await _audioPlayer.resume();
      }
    } catch (e) {
      print('切换播放状态失败: $e');
      rethrow;
    }
  }

  Future<void> stop() async {
    try {
      await _audioPlayer.stop();
      _currentSong = null;
    } catch (e) {
      print('停止播放失败: $e');
      rethrow;
    }
  }

  void dispose() {
    _audioPlayer.dispose();
  }

  Future<void> playPrevious() async {
    if (_playlist.isEmpty || _currentSong == null) return;

    int prevIndex;
    if (_isRandomPlay) {
      prevIndex = _random.nextInt(_playlist.length);
    } else {
      int currentIndex = _playlist.indexWhere((song) => song.songId == _currentSong?.songId);
      prevIndex = (currentIndex - 1 + _playlist.length) % _playlist.length;
    }

    await playSong(_playlist[prevIndex]);
  }

  Future<void> seek(Duration duration) async {
    try {
      await _audioPlayer.seek(duration);
    } catch (e) {
      print('调整播放进度失败: $e');
      rethrow;
    }
  }
}